package com.jrfid.smartcabinet.demo.ui.cabinet_config

import android.app.Application
import android.graphics.Canvas
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.navigation.NavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.listener.OnItemSwipeListener
import com.jrfid.smartcabinet.demo.R
import com.jrfid.smartcabinet.demo.base.BaseViewModel
import com.jrfid.smartcabinet.demo.model.CabinetConfigInfoModel
import com.jrfid.smartcabinet.demo.ui.cabinet_config.adapter.CabinetConfigAdapter
import com.jrfid.smartcabinet.demo.utils.Config
import com.jrfid.smartcabinet.demo.utils.TCPConnectUtils
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter
import java.lang.Exception

class CabinetConfigViewModel(application: Application, navController: NavController) : BaseViewModel(application, navController) {

    val adapter = CabinetConfigAdapter()

    init {
        adapter.draggableModule.isSwipeEnabled = true
        adapter.draggableModule.itemTouchHelperCallback.setSwipeMoveFlags(ItemTouchHelper.UP)
        adapter.draggableModule.setOnItemSwipeListener(object : OnItemSwipeListener {
            override fun onItemSwipeStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {

            }

            override fun clearView(viewHolder: RecyclerView.ViewHolder?, pos: Int) {

            }

            override fun onItemSwiped(viewHolder: RecyclerView.ViewHolder?, pos: Int) {

            }

            override fun onItemSwipeMoving(canvas: Canvas?, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float, isCurrentlyActive: Boolean) {

            }
        })
        adapter.setOnItemChildClickListener { a, view, position ->
            when (view.id) {
                R.id.btn_test_rfid -> {
                    val item = adapter.data[position]
                    val ip = item.readerIP.get()
                    if (ip.isNullOrEmpty()) {
                        ToastUtils.showShort(getString(R.string.text_cabinet_config_rfid_ip_hint))
                        return@setOnItemChildClickListener
                    }
                    val port = item.readerPort.get()
                    if (port.isNullOrEmpty()) {
                        ToastUtils.showShort(getString(R.string.text_cabinet_config_rfid_port_hint))
                        return@setOnItemChildClickListener
                    }
                    testConnect(ip, port)
                }
                R.id.btn_test_ic -> {
                    val item = adapter.data[position]
                    val ip = item.icIP.get()
                    if (ip.isNullOrEmpty()) {
                        ToastUtils.showShort(getString(R.string.text_cabinet_config_ic_ip_hint))
                        return@setOnItemChildClickListener
                    }
                    val port = item.icPort.get()
                    if (port.isNullOrEmpty()) {
                        ToastUtils.showShort(getString(R.string.text_cabinet_config_ic_port_hint))
                        return@setOnItemChildClickListener
                    }
                    testConnect(ip, port)
                }
                R.id.btn_test_finger -> {
                    val item = adapter.data[position]
                    val ip = item.fingerIP.get()
                    if (ip.isNullOrEmpty()) {
                        ToastUtils.showShort(getString(R.string.text_cabinet_config_finger_ip_hint))
                        return@setOnItemChildClickListener
                    }
                    val port = item.fingerPort.get()
                    if (port.isNullOrEmpty()) {
                        ToastUtils.showShort(getString(R.string.text_cabinet_config_finger_port_hint))
                        return@setOnItemChildClickListener
                    }
                    testConnect(ip, port)
                }
            }
        }
        adapter.addData(Config.getCabinetList())
        if (adapter.data.isEmpty()) {
            adapter.addData(CabinetConfigInfoModel(true).apply { this.name.set(this.getPositionName(0)) })
        }
        val footer = LayoutInflater.from(application).inflate(R.layout.footer_cabinet_config_add, adapter.footerLayout)
        footer.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
        adapter.addFooterView(view = footer, index = 0, orientation = LinearLayout.HORIZONTAL)
        footer.findViewById<LinearLayout>(R.id.btn_add)?.setOnClickListener {
            adapter.addData(CabinetConfigInfoModel(false).apply {
                this.name.set(this.getPositionName(adapter.data.size))
            })
        }
    }

    private fun testConnect(ip: String, port: String) {
        val manager = TCPConnectUtils.getConnectionManager(ip, port.toIntOrNull() ?: 4001)
        if (manager.isConnect) {
            ToastUtils.showShort(getString(R.string.text_connect_successfully))
        } else {
            TCPConnectUtils.connectDevice(ip, port.toIntOrNull() ?: 4001, object : SocketActionAdapter() {
                override fun onSocketConnectionSuccess(info: ConnectionInfo, action: String?) {
                    super.onSocketConnectionSuccess(info, action)
                    ToastUtils.showShort(getString(R.string.text_connect_successfully))
                    TCPConnectUtils.getConnectionManager(info.ip, info.port).unRegisterReceiver(this)
                }

                override fun onSocketConnectionFailed(info: ConnectionInfo, action: String?, e: Exception?) {
                    super.onSocketConnectionFailed(info, action, e)
                    ToastUtils.showShort(getString(R.string.text_connect_error))
                    TCPConnectUtils.getConnectionManager(info.ip, info.port).unRegisterReceiver(this)
                }
            })
        }
    }

    fun onClickBackBtn(view: View) {
        navController.navigateUp()
    }

    fun onClickSaveBtn(view: View) {
        adapter.data.forEachIndexed { index, item ->
            if (item.name.get().isNullOrEmpty()) {
                if (item.isMain)
                    ToastUtils.showShort(getString(R.string.text_cabinet_name_empty))
                else
                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_name_empty_format, item.getPositionName(index)))
                return
            }
//            if (item.readerIP.get().isNullOrEmpty()) {
//                if (item.isMain)
//                    ToastUtils.showShort(getString(R.string.text_cabinet_reader_ip_empty))
//                else
//                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_reader_ip_empty_format, item.getPositionName(index)))
//                return
//            }
//            if (item.readerPort.get().isNullOrEmpty()) {
//                if (item.isMain)
//                    ToastUtils.showShort(getString(R.string.text_cabinet_reader_port_empty))
//                else
//                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_reader_port_empty_format, item.getPositionName(index)))
//                return
//            }
//            if (item.icIP.get().isNullOrEmpty()) {
//                if (item.isMain)
//                    ToastUtils.showShort(getString(R.string.text_cabinet_ic_ip_empty))
//                else
//                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_ic_ip_empty_format, item.getPositionName(index)))
//                return
//            }
//            if (item.icPort.get().isNullOrEmpty()) {
//                if (item.isMain)
//                    ToastUtils.showShort(getString(R.string.text_cabinet_ic_port_empty))
//                else
//                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_ic_port_empty_format, item.getPositionName(index)))
//                return
//            }
//            if (item.fingerIP.get().isNullOrEmpty()) {
//                if (item.isMain)
//                    ToastUtils.showShort(getString(R.string.text_cabinet_finger_ip_empty))
//                else
//                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_finger_ip_empty_format, item.getPositionName(index)))
//                return
//            }
//            if (item.fingerPort.get().isNullOrEmpty()) {
//                if (item.isMain)
//                    ToastUtils.showShort(getString(R.string.text_cabinet_finger_port_empty))
//                else
//                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_finger_port_empty_format, item.getPositionName(index)))
//                return
//            }
            if (item.address.get().isNullOrEmpty()) {
                if (item.isMain)
                    ToastUtils.showShort(getString(R.string.text_cabinet_address_empty))
                else
                    ToastUtils.showShort(getStringFormat(R.string.text_cabinet_address_empty_format, item.getPositionName(index)))
                return
            }
        }
        Config.saveCabinetList(adapter.data)
        ToastUtils.showShort(getString(R.string.text_save_successfully))
    }
}